import { Button, Input, Message } from '@arco-design/web-react';
import LoadingMask from '@src/components/loadingMask';
import { KeyboardEvent, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import main, { AppLocalKey } from '../../main';
import { userRequest } from '../../redux/userReducer';
import { apiLogin } from './api';

export default function LoginPage() {
  // 用户名
  const [username, setUsername] = useState('');
  // 密码
  const [password, setPassword] = useState('');
  // 记住密码
  const [remberPwd, setRemberPwd] = useState(false);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  useEffect(() => {
    let uname = localStorage.getItem(AppLocalKey.loginUsername);
    setUsername(uname || '');
    let upwd = localStorage.getItem(AppLocalKey.loginPassword);
    let isRember = localStorage.getItem(AppLocalKey.loginIsRember);
    if (isRember === 'true') {
      setPassword(upwd || '');
    }
    setRemberPwd(isRember === 'true');
    main.currPageNum = {};
    main.currPageSize = {};
    main.currPageState = {};
  }, []); //eslint-disable-line

  function verifyLoginField() {
    let res = true;
    if (!username) {
      res = false;
      Message.warning('请输入账号');
    } else if (!password) {
      res = false;
      Message.warning('请输入密码');
    }
    return res;
  }
  function handleKeyUp(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key === 'Enter') {
      handleLogin();
    }
  }
  async function handleLogin() {
    let verify = verifyLoginField();
    if (!verify) return;
    try {
      LoadingMask.show('正在登录...');
      let res = await apiLogin(username, password);
      let data = res.data;
      if (data.code === 200) {
        let token = data.data.access_token;
        main.loginKey = token;
        localStorage.setItem(AppLocalKey.loginToken, token);
        Message.success('登录成功');
        dispatch(userRequest({ token }));
        localStorage.setItem(AppLocalKey.loginUsername, username);
        localStorage.setItem(AppLocalKey.loginIsRember, remberPwd ? 'true' : 'false');
        if (remberPwd) {
          localStorage.setItem(AppLocalKey.loginPassword, password);
        } else {
          localStorage.removeItem(AppLocalKey.loginPassword);
        }
        navigate('/home');
      } else {
        Message.error(data.msg || '登录失败');
      }
    } catch (e: any) {
      Message.error(e.message || '登录失败');
    } finally {
      LoadingMask.hide();
    }
  }

  return (
    <div className="login-page bg-primary">
      <img className="pic-bg" src="/pic/pic_bg_login.png" alt="" />
      <div className="pic-logo-block d-flex-r">
        <img className="pic-logo" src="/pic/icon_logo.png" alt="" />
        <div className="name">海量</div>
      </div>
      <div className="content-block d-flex-r">
        <img className="pic-login-card" src="/pic/pic_login_card.jpg" alt="" />
        <div className="content d-flex-c ai-start jc-center">
          <div className="font-24 font-widget-600 mb-40">欢迎登录海量系统</div>
          <div className="text-second-color mb-5">账号</div>
          <Input
            className="m-input h-36 mb-30"
            value={username}
            onKeyUp={handleKeyUp}
            onChange={(v) => setUsername(v)}
          />
          <div className="text-second-color mb-5">密码</div>
          <Input
            type="password"
            className="m-input h-36 mb-30"
            value={password}
            onChange={(v) => setPassword(v)}
            onKeyUp={handleKeyUp}
          />
          <Button className="bw-100 mb-60 mt-30" type="primary" shape="round" size="large" onClick={handleLogin}>
            登录
          </Button>
        </div>
      </div>
      <div className="copy-right text-second-color font-12">
        Copyright © 2021-2022 河南天诺 信息技术有限公司 All Rights Reserved.
      </div>
    </div>
  );
}
